package fragmentparent;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.wq.cycling.DemoApplication;
import com.wq.cycling.R;

import activity.SonActivity;
import bean.EntityForSimple;
import bean.MessageForSimpleList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import service.ApiUtil;
import util.Constant;
import util.MySharePerference;

import static com.wq.cycling.R.id.iv_delete;
import static com.wq.cycling.R.id.tv_mydevice;


/**
 * author：wangqi on 2017/4/26 17:48
 * email：773630555@qq.com
 */
public class Fragment_A extends Fragment implements OnMarkerClickListener, AMap.OnMyLocationChangeListener {

    private View rootView;
    private int slidehigh = 400;
    private View ll_show;
    //监听滑动状态
    //地图
    private MapView mapView;
    private AMap aMap;
    private LatLng mylatlng;
    /**
     * mode 0基础地图1卫星地图 road 0路况模式 1非路况模式
     */
    private int mode = 0, road = 0;
    private Intent intent;
    private Bundle bundle;
    private GeocodeSearch geocoderSearch;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_fragment_a, container, false);
        /*初始化地图和amap对象*/
        mapView = (MapView) rootView.findViewById(R.id.map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        initView();
        initMapView();
        return rootView;
    }

    private void initView() {
        rootView.findViewById(R.id.iv_mapmode).setOnClickListener(listener);
        rootView.findViewById(R.id.ll_road).setOnClickListener(listener);
        rootView.findViewById(R.id.iv_plus).setOnClickListener(listener);
        rootView.findViewById(R.id.iv_reduce).setOnClickListener(listener);
        rootView.findViewById(iv_delete).setOnClickListener(listener);
        rootView.findViewById(R.id.iv_message).setOnClickListener(listener);
        rootView.findViewById(tv_mydevice).setOnClickListener(listener);

    }

    public void initData() {
        ApiUtil.getApiService().getDevices(DemoApplication.getToken()).enqueue(new Callback<MessageForSimpleList>() {
            @Override
            public void onResponse(Call<MessageForSimpleList> call, Response<MessageForSimpleList> response) {
                try {
                    MessageForSimpleList entity = response.body();
                    if (entity.getCode().equals("10008")) {
                        aMap.clear();
                        EntityForSimple mData = null;
                        if (entity.getData().size() > 0) {
                            for (EntityForSimple data : entity.getData()) {
                                if (data.getDeviceid().equals(DemoApplication.getDeviceid())) {
                                    mData = data;
                                }
                            }
                            if (mData == null) {
                                mData = entity.getData().get(0);
                            }
                            DemoApplication.setDeviceid(mData.getDeviceid());
                            initHintData(mData);
                            getAddress(mData.getLat(), mData.getLng());
                            ((TextView) rootView.findViewById(tv_mydevice)).setText(mData.getDevicename());
                            if(!mData.getImei().isEmpty()) {
                                MySharePerference.addSharePerference(getActivity(),"IMEI","has");
                                initMarker(mData.getLat(), mData.getLng());
                            }else{
                                MySharePerference.addSharePerference(getActivity(),"IMEI","");
                            }
                        }
                    } else {
                        Toast.makeText(getActivity(), entity.getMsg(), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<MessageForSimpleList> call, Throwable t) {
                Log.d("exception", t.getMessage());
                Toast.makeText(getActivity(), getResources().getString(R.string.error), Toast.LENGTH_LONG).show();
            }
        });
    }


    public View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.iv_mapmode:
                    if (mode == 0) {
                        ((ImageView) v).setImageResource(R.mipmap.icon_right_map3);
                        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);
                        mode = 1;
                    } else {
                        ((ImageView) v).setImageResource(R.mipmap.icon_right_map2);
                        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                        mode = 0;
                    }
                    break;
                case R.id.ll_road:
                    if (road == 0) {
                        ((ImageView) rootView.findViewById(R.id.iv_road)).setImageResource(R.mipmap.icon_right_map5);
                        aMap.setTrafficEnabled(true);
                        road = 1;
                    } else {
                        ((ImageView) rootView.findViewById(R.id.iv_road)).setImageResource(R.mipmap.icon_right_map4);
                        aMap.setTrafficEnabled(false);
                        road = 0;
                    }
                    break;
                case R.id.iv_plus:
                    aMap.moveCamera(CameraUpdateFactory.zoomIn());
                    break;
                case R.id.iv_reduce:
                    aMap.moveCamera(CameraUpdateFactory.zoomOut());
                    break;
                case iv_delete:
                    HideOrderList();
                    break;
                case R.id.iv_message:
                    intent = new Intent(getActivity(), SonActivity.class);
                    bundle = new Bundle();
                    bundle.putInt("code", Constant.MessageList);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    break;
                case tv_mydevice:
                    intent = new Intent(getActivity(), SonActivity.class);
                    bundle = new Bundle();
                    bundle.putInt("code", Constant.DeviceList);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 初始化地图组件
     */
    private void initMapView() {
        //隐藏缩放组件
        aMap.getUiSettings().setZoomControlsEnabled(false);
        //logo位置
        aMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);
        //注册点击事件
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        aMap.setOnMyLocationChangeListener(this);
        initGeocoder();
        //initMarker();
        //加载定位maker
        aMap.moveCamera(CameraUpdateFactory.zoomTo(16));
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));//设置定位蓝点精度圆圈的填充颜色的方法。
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_arrows));// 设置小蓝点的图标
        myLocationStyle.anchor(0.5f, 0.8f);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//指定为一次并拉到中心
        //myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//指定为一次并拉到中心
        myLocationStyle.interval(60000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
    }

    /**
     * 添加设备列表的marker
     */
    private void initMarker(String lat, String lng) {
        LatLng latLng = new LatLng(Double.parseDouble(lat), Double.parseDouble(lng));
        aMap.addCircle(new CircleOptions().
                center(latLng).
                radius(200).
                fillColor(Color.argb(25, 1, 139, 250)).
                strokeColor(Color.argb(100, 1, 139, 250)).
                strokeWidth(2));

        MarkerOptions markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .fromBitmap(BitmapFactory.decodeResource(getResources(), DemoApplication.getmarker("1"))))
                .position(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)))
                .draggable(true);
        aMap.addMarker(markerOption);

        //如果想改变地图中心点
        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(new LatLng(Double.parseDouble(lat), Double.parseDouble(lng)), 16, 0, 0)));

    }

    public static Fragment_A newInstance() {
        Fragment_A fragment = new Fragment_A();
        return fragment;
    }

    /**
     * 初始化定位蓝点
     */
    public void locationBlue() {
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));//设置定位蓝点精度圆圈的填充颜色的方法。
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.map_arrows));// 设置小蓝点的图标
        myLocationStyle.anchor(0.5f, 0.8f);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//指定为一次并拉到中心
        //myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//指定为一次并拉到中心
        myLocationStyle.interval(60000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
        ll_show = rootView.findViewById(R.id.ll_show);
        try {
            int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            ll_show.measure(widthSpec, heightSpec);
            slidehigh = ll_show.getMeasuredHeight();
        } catch (Exception e) {
            slidehigh = 400;
        }
        initData();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        //反地理编码
        ShowOrderList();
        return false;
    }

    /**
     * 初始化逆地理编码组件
     */
    private void initGeocoder() {
        geocoderSearch = new GeocodeSearch(getActivity());
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult result, int rCode) {

                if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                    if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) {
                        ((TextView) rootView.findViewById(R.id.tv_address)).setText(result.getRegeocodeAddress().getFormatAddress());
                    } else {
                        Toast.makeText(getActivity(), "无数据", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(getActivity(), rCode, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });
    }

    public void getAddress(String latitude, String longitude) {
        LatLonPoint latLonPoint = new LatLonPoint(Double.parseDouble(latitude), Double.parseDouble(longitude));
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
    }

    /**
     * 显示操作面板
     */
    private void ShowOrderList() {
        if (ll_show.getVisibility() == View.GONE) {
            ll_show.setVisibility(View.VISIBLE);
            TranslateAnimation anim = new TranslateAnimation(0, 0, slidehigh, 0);
            anim.setDuration(300);
            ll_show.startAnimation(anim);
        }
    }

    /**
     * 隐藏操作面板
     */
    private void HideOrderList() {
        if (ll_show.getVisibility() == View.VISIBLE) {
            ll_show.setVisibility(View.GONE);
            TranslateAnimation anim = new TranslateAnimation(0, 0, 0, slidehigh);
            anim.setDuration(300);
            ll_show.startAnimation(anim);
        }
    }


    /**
     * 定位成功后的回调
     *
     * @param location
     */
    @Override
    public void onMyLocationChange(Location location) {
        if (location != null) {
            mylatlng = new LatLng(location.getLatitude(), location.getLongitude());
        }
    }

    /**
     * 动态写入每个设备的显示信息
     */
    private void initHintData(EntityForSimple mdata) {
        ((TextView) rootView.findViewById(R.id.tv_devicename)).setText(mdata.getDevicename());
        ((TextView) rootView.findViewById(R.id.tv_power)).setText(mdata.getPower() + getResources().getString(R.string.unit2));
        ((ImageView) rootView.findViewById(R.id.iv_power)).setImageResource(DemoApplication.getPower(mdata.getPower()));
        ((TextView) rootView.findViewById(R.id.tv_state)).setText(mdata.isonline() ? getResources().getString(R.string.online) : getResources().getString(R.string.up_pull_leave));
        ((TextView) rootView.findViewById(R.id.tv_time)).setText(mdata.getReporttime());
    }
}
